package a2022.a20220907;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author lenovo
 * @date 2022/9/7
 */
public class a {
    public static void main(String[] args) {
        System.out.println(reorderSpaces("  hello"));
        System.out.println(reorderSpacesTwo("  hello"));
    }

    public static String reorderSpaces(String text) {
        int spaceNum = 0, num = 0, x = 0, y = 0, size = text.length();
        String s = text + " ";
        List<String> list = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            num = i + 1;
            char c = text.charAt(i);
            if (text.charAt(i) == ' ') {
                spaceNum++;
                if (x <= i) {
                    x = i+1;
                }
            }
            if (s.charAt(num) == ' ' && x <= i) {
                String str = text.substring(x, i+1);
                list.add(str);
            }
        }
        num = list.size() - 1;
        x = num == 0 ? spaceNum % 1 : spaceNum % num;
        y = num == 0 ? spaceNum / 1 : spaceNum / num;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < num; i++) {
            sb.append(list.get(i)).append(String.join("", Collections.nCopies(y, " ")));
        }
        sb.append(list.get(num)).append(String.join("", Collections.nCopies(x, " ")));
        if (num == 0){
            sb.append(String.join("", Collections.nCopies(y, " ")));
        }
        return sb.toString();
    }

    public static String reorderSpacesTwo(String s) {
        int n = s.length(), cnt = 0;
        List<String> list = new ArrayList<>();
        for (int i = 0; i < n; ) {
            if (s.charAt(i) == ' ' && ++i >= 0 && ++cnt >= 0) continue;
            int j = i;
            while (j < n && s.charAt(j) != ' ') j++;
            list.add(s.substring(i, j));
            i = j;
        }
        StringBuilder sb = new StringBuilder();
        int m = list.size(), t = cnt / Math.max(m - 1, 1);
        String k = "";
        while (t-- > 0) k += " ";
        for (int i = 0; i < m; i++) {
            sb.append(list.get(i));
            if (i != m - 1) sb.append(k);
        }
        while (sb.length() != n) sb.append(" ");
        return sb.toString();
    }

}
